package fun.codedesign.jdk.math;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;


public class FiveCharTestDemo {
    public static void main(String[] args) {

        char[] answer, input;
        int[] result;
        int count = 0;
        answer = generate(5);
        System.out.println(answer);
        //userinput();
        //System.out.println();
        char[] bye = {'b', 'y', 'e'};
        for (; ; ) {
            input = userinput();
            if (Arrays.equals(input, bye)) {
                System.out.println("退出游戏");
                break;
            }
            count++;  //count
            result = check(answer, input);
            show(count, result);
            if (result[0] == 5 && result[1] == 5) {
                System.out.println("答对了");
                break;
            }
        }
    }

    public static char[] generate(int n) {
        char[] chs = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
        boolean[] used = new boolean[chs.length];
        char[] answer = new char[n];

        int i = 0;
        int index;
        Random rd = new Random();

        do {
            index = rd.nextInt(chs.length);
            if (used[index]) {
                continue;
            }
            answer[i++] = chs[index];
            used[index] = true;
        } while (i < n);
        return answer;
    }

    public static char[] userinput() {
        try(Scanner in = new Scanner(System.in)) {
            char[] input = {};
            System.out.println("输入:");
            String str = in.nextLine();
            input = str.toCharArray();
            return input;
        }
    }


    public static int[] check(char[] answer, char[] input) {
        int[] result = {0, 0};
        int i, j = 0;
        for (i = 0; i < answer.length; i++) {
            for (j = 0; j < input.length; j++) {
                if (answer[i] == input[j]) {
                    result[0]++;
                    if (i == j) {
                        result[1]++;
                    }
                    break;
                }
            }
        }
        return result;
    }

    public static void show(int count, int[] result) {
        System.out.println("答题" + count + "次");
        System.out.println("匹配字符" + result[0] + "	个");
        System.out.println("匹配位置" + result[1] + " 个");
        if (result[0] == 5 && result[1] == 5) {
            System.out.println("答对了");
        }
    }

}
